package com.maingel.showcase.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.maingel.showcase.R;
import com.maingel.showcase.as.TimerService;
import com.maingel.showcase.entity.User;
import com.maingel.showcase.event.TimerEvent;

import de.greenrobot.event.EventBus;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;

@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity {
    @InjectView(R.id.main_username)
    private TextView usernameTextView;
    @InjectView(R.id.main_gender)
    private TextView genderTextView;
    @InjectView(R.id.main_age)
    private TextView ageTextView;
    @InjectView(R.id.main_start_service)
    private Button startServiceButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(MainActivity.this);

        Intent intent = getIntent();
        User user = (User) intent.getSerializableExtra("user");
        usernameTextView.setText(user.getUsername());
        genderTextView.setText(user.getGender() + "");
        ageTextView.setText(user.getAge() + "");

        startServiceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startService();
                startServiceButton.setEnabled(false);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(MainActivity.this);
        stopService(new Intent(MainActivity.this, TimerService.class));
    }

    private void startService(){
        startService(new Intent(MainActivity.this, TimerService.class));
    }

    public void onEventMainThread(TimerEvent event) {
        if(!"-1".equals(event.getIndex())){
            Toast.makeText(MainActivity.this, event.getIndex(), Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(MainActivity.this, "Android服务已到时停止。", Toast.LENGTH_SHORT).show();
        }
    }
}
